import sys
import os
import string
import urllib
import urllib2
import re

from XbmcHandler import *


CACHE_PATH=safeTranslatePath(os.path.join( os.getcwd(), 'resources', 'cache' ))
COOKIE_PATH=safeTranslatePath(os.path.join( os.getcwd(), 'resources', 'cookie.wpl' ))

__plugin__ = "All in one plugin"
    
###############################################################################################    
def ReadUrlPageData(url, decode_url=True):
    if decode_url:
        url = urllib.unquote_plus(url)
        url = urllib.unquote(url).replace("&amp;", "&")
    req = urllib2.Request(url)
    req.add_header('User-Agent', ' Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
    response = urllib2.urlopen(req)
    source = response.read()            # Holds the webpage that was read via the response.read() command.  
    response.close()   
    return source
###############################################################################################

def ExtractLink(source, startStr, endStr):
    start = source.find(startStr)
    if(start == -1): return ''
    start = start +  len(startStr)
    end = source[start:].find(endStr)
    if(end != -1): end = start + end
    if(end == -1): end=len(source)
    return source[start:end].strip()    

###############################################################################################
def GetMatches(url, pattern):
    page = ReadUrlPageData(url)
    matches=re.compile(pattern).findall(page)
    return matches   

###############################################################################################
def GetMatchInSource(source, pattern):
    matches=re.compile(pattern).match(source)
    return matches

###############################################################################################
def GetMatchesInSource(source, pattern):
    matches=re.compile(pattern).findall(source)
    return matches
      
    
###############################################################################################    
def SortItems(x, y):
    x_hebrewtitle = x[2]
    y_hebrewtitle = y[2]
        
    if (x_hebrewtitle > y_hebrewtitle):
        return 1
    elif (x_hebrewtitle < y_hebrewtitle):
        return -1
    else:
        return 0 
        
def Debug(message, Verbose=True):
    if (Verbose):
        # repr() is used, got wierd issues with unicode otherwise, since we send mixed string types (eg: unicode and ascii) 
        #xbmc.log( "[PLUGIN] '%s: %s'!" % ( __plugin__, message, ), xbmc.LOGNOTICE )
        print( "[PLUGIN] '%s: %s'!" % ( __plugin__, message, ))
    elif (not Verbose):
        # repr() is used, got wierd issues with unicode otherwise, since we send mixed string types (eg: unicode and ascii) 
        #xbmc.log( "[PLUGIN] '%s: %s'!" % ( __plugin__, message, ), xbmc.LOGNOTICE )
        print( "[PLUGIN] '%s: %s'!" % ( __plugin__, message, ))

def GetPluginPath():
    try:
        import xbmcaddon        
        settings = xbmcaddon.Addon(id='plugin.all.in.one.plugin')
        plugin_path = settings.getAddonInfo('path')
        return plugin_path   
    except:
        return "C:\\Program Files\\XBMC\\addons\\plugin.all.in.one.plugin"
    
def GetUserGuid():
    try:
        import xbmc
        import os        
        plugin_path = GetPluginPath()   
        userGuidFilePath = xbmc.translatePath(os.path.join(plugin_path, 'Resources', 'cache', 'user_guid.dat'))
        print "GetUserGuid: %s" % userGuidFilePath
        user_guid = ""        
        if (os.path.exists(userGuidFilePath)):
            print "userGuidFilePath found reading value"
            userFile = file(userGuidFilePath, 'r')
            user_guid = userFile.read()
            userFile.close()
        return user_guid
    except:
        return 123456
    

def WriteUserGuid(user_guid, userGuidFilePath):
    print "WriteUserGuid to path: %s - %s" % (user_guid, userGuidFilePath)
    userFile = file(userGuidFilePath, 'w')
    userFile.write(str(user_guid))
    userFile.close()
    
def CheckIfFirstRun():
    global CONFIG_PATH
    if (os.path.exists(CONFIG_PATH)):
        return False
    else:
        return True
    
def CheckIfUpgrade():
    return False

def CheckForNewVersion():
    return

def loadCache(filename):    
    filename = filename.replace('.', ''). replace('/','').replace(':','').replace('?','').replace('-','')
    filename = safeTranslatePath( os.path.join( CACHE_PATH, filename ) ) 
    #Debug('Loading from cache: ' + filename)

    title = ""
    plot = ""
    image = ""
    streamurl = ""

    try:
        if (os.path.exists(filename)):
            #Debug('Cache hit: ' + filename)
            cachefile = file(filename, 'r')
            filecontents = cachefile.read()
            title = filecontents.split('%%$$')[0]
            plot = filecontents.split('%%$$')[1]
            image = filecontents.split('%%$$')[2]
            streamurl = filecontents.split('%%$$')[3]
        else:
            Debug('Cache miss: ' + filename)
            return False
    except:
        Debug('Cache exception')
        return False
    
    return title, plot, image, streamurl

def saveCache(filename, title, plot, image, streamurl):

    filecontents = title + '%%$$' + plot + '%%$$' + image + '%%$$' + streamurl
    filename = filename.replace('.', ''). replace('/','').replace(':','').replace('?','').replace('-','').replace(';','')
    filename = safeTranslatePath( os.path.join( CACHE_PATH, filename ) ) 
    Debug('Saving to cache: ' + filename)

    try:
        cachefile = file(filename, 'w')
        cachefile.write (filecontents)
        cachefile.close()
    except IOError:
        Debug( "I/O error({0}) %s" % (IOError))
        return False
    except ValueError:
        Debug("Could not convert data to an integer.")
        return False
    except:
        Debug("Unexpected error:", sys.exc_info()[0])        
        Debug('Cache exception')
        return False
    
def clearCache():
    filename = safeTranslatePath( os.path.join( CACHE_PATH, name ) ) 
    
def GetParams(sysArgs):    
    param=[]
    if(len(sysArgs) == 0):
        return {}
    
    paramstring=sysArgs
    paramstring = paramstring
    if(paramstring[0] == "?"):
        paramstring = paramstring[1:]
    #Remove site name
    startOfParams = paramstring.find("?")
    if(startOfParams != -1):
        paramstring = paramstring[startOfParams+1:]
        
    Debug( 'get_params %s' % paramstring, True)
    if len(paramstring)>=2:
        pairsofparams=paramstring.split('&')
        param={}
        for i in range(len(pairsofparams)):
            delimiterIndex = pairsofparams[i].find("=")
            firstItem = pairsofparams[i][0:delimiterIndex]
            secondItem = pairsofparams[i][delimiterIndex+1:len(pairsofparams[i])]
            
            param[firstItem]=secondItem
  
    return param

def GetParam(dataCollection, paramName, defaultValue):
    try:
        return dataCollection[paramName]
    except:
        return defaultValue